package cn.schoolwow.ams.test.module.quickdao.aware;

import cn.schoolwow.ams.domain.block.list.clazz.ClazzListBlockConfigAware;
import cn.schoolwow.ams.domain.block.list.clazz.ClazzListBlockOption;
import cn.schoolwow.ams.domain.block.list.clazz.crud.ClazzListBlockListListener;
import cn.schoolwow.ams.domain.block.list.common.ListBlockPagingResponse;
import cn.schoolwow.ams.test.module.quickdao.domain.DatabaseProperty;
import cn.schoolwow.quickdao.domain.DAO;
import cn.schoolwow.quickdao.domain.entity.Property;
import cn.schoolwow.util.domain.beanCopy.BeanCopy;
import cn.schoolwow.util.domain.query.instanceList.QueryInstanceList;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.Validate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DatabasePropertyAware extends ClazzListBlockConfigAware {
    @Autowired
    private DAO starterDAO;

    @Override
    public ClazzListBlockOption getAMSBlockConfig() {
        ClazzListBlockOption clazzListBlockOption = new ClazzListBlockOption(
                "test", "数据库字段", DatabaseProperty.class
        );
        clazzListBlockOption.listBlockShowOption.requestFieldNames = new String[]{"column"};
        clazzListBlockOption.clazzListBlockAPIListener.listListener = new ClazzListBlockListListener() {
            @Override
            public ListBlockPagingResponse list(JSONObject conditionMap) throws Exception {
                String tableName = conditionMap.getString("tableName");
                Validate.notEmpty(tableName, "表名不能为空");
                List<Property> propertyList = starterDAO.getPropertyList(tableName);
                if(conditionMap.containsKey("column")){
                    propertyList = QueryInstanceList.newQuery(propertyList)
                            .addQuery("column", conditionMap.getString("column"))
                            .execute()
                            .getList();
                }
                List<DatabaseProperty> databasePropertyList = BeanCopy.cloneObjectList(propertyList, DatabaseProperty.class);
                for(DatabaseProperty databaseProperty:databasePropertyList){
                    databaseProperty.tableName = tableName;
                }
                return new ListBlockPagingResponse(databasePropertyList);
            }
        };
        return clazzListBlockOption;
    }
}
